package lab2;

public class ConsoleProgressBar {
    private StringBuilder progress;
    private String name;
//
//    public static void main(String[] args) {
//        ConsoleProgressBar bar = new ConsoleProgressBar("");
//
//        System.out.println("Process Starts Now!");
//
//        bar.update(0, 1000);
//        for(int i=0;i<1000;i++) {
//            // do something!
//            for(int j=0;j<10000000;j++)
//                for(int p=0;p<10000000;p++);{
//                // 	update the progress bar
//                bar.update(i, 1000);
//            }
//        }
//        System.out.println("Process Completed!");
//    }

    /**
     * initialize progress bar properties.
     */
    public ConsoleProgressBar(String _name) {
        this.name = _name;
        init();
    }

    /**
     * called whenever the progress bar needs to be updated.
     * that is whenever progress was made.
     *
     * @param done an int representing the work done so far
     * @param total an int representing the total work
     */
    public void update(int done, int total) {
        char[] workchars = {'|', '/', '-', '\\'};
        String format = "\r%s %3d%% %s %c";

        int percent = (++done * 100) / total;
        int extrachars = (percent / 2) - this.progress.length();

        while (extrachars-- > 0) {
            progress.append('█');
        }

        System.out.printf(format, this.name, percent, progress,
                workchars[done % workchars.length]);
        if (done == total) {
            System.out.flush();
            System.out.println();
            init();
        }
    }
    public String getUpdateStr(int done, int total) {
        char[] workchars = {'|', '/', '-', '\\'};
        String format = "\r%s %3d%% %s %c";
        format = " %s %2d %s %c";

//        int percent = (++done * 100) / total;
        int percent = done;
        int extrachars = (percent / 2) - this.progress.length();

        while (extrachars-- > 0) {
            progress.append('█');
        }

        String str = String.format(format, this.name, percent, progress,
                workchars[done % workchars.length]);
        return str;
    }

    private void init() {
        this.progress = new StringBuilder(60);
    }
}

